package cn.itsource.wechat.controller;

import cn.hutool.core.util.IdUtil;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.org.domain.LoginInfo;
import cn.itsource.wechat.domain.BinderDto;
import cn.itsource.wechat.domain.WechartProperties;
import cn.itsource.wechat.service.IWeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/wechart")
public class WechartController {

    @Autowired
    private WechartProperties wechartProperties;

    @Autowired
    private IWeChatService weChatService;

    //申请微信登录
    @GetMapping("/apply")
    public String apply() {
        //https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect
        //生成一个唯一标识作为state
        String state = IdUtil.fastSimpleUUID();
        //生成完整的授权码URL
        String authorizationCodeUrl = String.format(wechartProperties.getAuthorizationCodeUrl(), wechartProperties.getAppId(), wechartProperties.getRedirectUri(), state);
        return "redirect:" + authorizationCodeUrl;
    }

    @GetMapping("/callback")
    public String callback(String code) {
        return weChatService.callback(code);
    }

    @PostMapping("/binder")
    @ResponseBody //返回json格式
    public AjaxResult binder(@RequestBody BinderDto binderDto) {
        LoginInfo result = weChatService.binder(binderDto);
        return AjaxResult.ok(result);
    }
}